"""
获取搜狐网首页的图片并保存到指定文件夹下
"""
import re

import requests


def download_image(url):
    resp = requests.get(url)
    filename = url[url.rfind('/') + 1:]
    with open(f'sohu/{filename}', 'wb') as file:
        file.write(resp.content)


def main():
    pattern = re.compile(r'<img\s.*?src="(.+?)".*?>')
    resp = requests.get('https://www.sohu.com/')
    if resp.status_code == 200:
        image_links = pattern.findall(resp.text)
        for image_link in image_links:
            if image_link.startswith('//'):
                image_link = 'http:' + image_link
            download_image(image_link)
    print('程序结束!!!')


if __name__ == '__main__':
    main()
